package com.hk.admin.spring.interceptor;

import com.hk.admin.common.constant.GlobalConstants;
import com.hk.admin.common.exception.HKAdminException;
import com.hk.admin.common.model.system.UserModel;
import com.hk.admin.common.util.UserDetailUtil;
import com.hk.admin.spring.config.HKAdminConfig;
import com.hk.admin.spring.security.UserDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
import java.util.List;

/**
 * <br>
 * <b>功能：</b>菜单权限拦截器<br>
 * <b>作者：</b>Pan.ShiJu<br>
 * <b>日期：</b>2017/4/11 23:27<br>
 */
@Component
public class MenuAuthInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private HKAdminConfig hkAdminConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.debug("---------------拦截器开始---------------");
        // 忽略的请求路径，直接通过
        if (hkAdminConfig.getIgnoredUrl().contains(request.getRequestURI())) return true;

        // 判断当前登录人的权限
        UserDetail principal = UserDetailUtil.getCurrentUserDetail();
        // 没有登录直接不通过
        if (principal == null) return false;

        String uri = request.getRequestURI();
        if (principal.getPathInvariable().contains(uri)) return true;

        String[] uris = getURIDirs(uri);
        List<String[]> pathVariable = principal.getPathVariable();
        boolean matchResult = matchURI(uris, pathVariable);
        if (!matchResult) {
            // 没权限返回401
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, GlobalConstants.ERROR_401);
        }
        logger.debug("---------------拦截器结束---------------");
        // 只有返回true才会继续向下执行，返回false取消当前请求
        return matchResult;
    }

    private boolean matchURI(String[] uris, List<String[]> pathVariable) {
        for (String[] paths : pathVariable) {
            if (uris.length != paths.length) {
                continue;
            }
            boolean flag = false;
            for (int i = 0; i < paths.length; i++) {
                if (paths[i].contains(GlobalConstants.OPEN_BRACE) && paths[i].contains(GlobalConstants.CLOSE_BRACE)) {
                    continue;
                }
                if (!paths[i].equals(uris[i])) {
                    flag = false;
                    break;
                }
                flag = true;
            }
            if (flag) {
                return true;
            }
        }
        return false;
    }

    private String[] getURIDirs(String uri) {
        if (uri.startsWith(GlobalConstants.LEFT_SLASH)) {
            uri = uri.replaceFirst(GlobalConstants.LEFT_SLASH, GlobalConstants.EMPTY_STRING);
        }
        return uri.split(GlobalConstants.LEFT_SLASH);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

}
